#include "main.h"
#include "netconf.h"
#include "stm32f4xx_hal.h"
#include "stm32f4xx_hal_rcc.h"
#include "stm32f4xx_hal_pwr.h"
#include "stm32f4xx_hal_gpio_ex.h"
#include "RTC_calendar.h"
#include "globals.h"
#include "netpacket.h"
#include "api.h"
#include "tcp.h"
#include "gsm.h"

#define SYSTEM_FREQ 			168000000

sStartParam startParam;
uint8_t bootMode;
USBD_HandleTypeDef USBD_Device;
void NetWorkInit(void *pvParameters);

int main(void)
{
	SystemInit();
	HAL_Init();
	SystemClock_Config();
	RTC_CalendarInit();
	BuzzerInit();
	Flash_Mem_Init();

	/* Get system Freq */
	if(HAL_RCC_GetSysClockFreq() != SYSTEM_FREQ)
		Error_Handler();

	if (Flash_M25P64_Read_ID() != _FLASH_M25P64_ID)
		Error_Handler();
	ParamInit();
	KeyGPIO_Init();
	SSD1306_GPIO_Init();
	SSD1306_Init();
	/* LCD captions */
	LCD_ClearFull();
	LCD_DrawImageFullScreen((uint8_t*)&OLED_Logo);

	GSM_periph_Init();
	xTaskCreate(MenuTask, NULL, 1024, NULL, tskIDLE_PRIORITY, NULL);

	if(BACUP_STATUS->BACUP_STATUS_REG & USB_ENABLED)
	{
		HAL_PWR_EnableBkUpAccess();
		BACUP_STATUS->BACUP_STATUS_REG = USB_DISABLED;
		HAL_PWR_DisableBkUpAccess();
		xTaskCreate(UsbConfigTask, NULL, 384, NULL, tskIDLE_PRIORITY, NULL);
		ModbusInit();
		bootMode = BOOT_MODE_USB;
	}
	else
		xTaskCreate(NetWorkTask, NULL, 2048, NULL, tskIDLE_PRIORITY+2, NULL);

	vTaskStartScheduler();
}
